<template>
  <div class="automation-add">
    <h1 class="back-title"><i class="iconfont icon-fanhui goback" @click="$router.go(-1)"></i>{{title}}邮件规则</h1>
    <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
      <div class="line">
        <el-form-item label="规则名称：" prop="name">
          <el-input v-model="ruleForm.name" size="small" style="width:200px" maxlength="20"
                    placeholder="请输入邮件规则名称"></el-input>
        </el-form-item>
        <el-form-item label="邮箱选择：" prop="sendEmail" style="margin-left: 30px">
          <el-select v-model="ruleForm.sendEmail" placeholder="请选择邮箱" size="small">
            <el-option v-for="item in common.emailList" :key="item.emailAddr"
                       :label="item.emailAddr" :value="item.emailAddr"></el-option>
          </el-select>
        </el-form-item>
      </div>
      <el-form-item label="有效时间：" prop="timeArr">
        <el-date-picker size="small" :clearable="false"
                        v-model="ruleForm.timeArr" :picker-options="pickerOptions"
                        type="datetimerange" value-format="yyyy-MM-dd HH:mm:ss"
                        range-separator="至"
                        start-placeholder="开始日期"
                        end-placeholder="结束日期">
        </el-date-picker>
      </el-form-item>
      <!-- 下面具体展示-->
      <el-form-item label="规则详情：" prop="templates">
        <!--顶部-->
        <div class="rule-detail">
          <div class="top">
            <div class="box">
              <div class="inner">
                <h1>请选择目标用户：</h1>
                <el-cascader size="small" v-model="cutGroupIdArr"
                             class="input"
                             props.checkStrictly=true @change="(value) => handleChange(value, 'cutGroupId')"
                             change-on-select
                             :options="treeMan"
                             :props="{ expandTrigger: 'hover',label: 'text', value: 'id', children: 'children'}"
                ></el-cascader>
              </div>
            </div>
          </div>
          <div class="the-frag">
            <img class="next" src="../../../../public/img/icon/auto-bottom.png" alt="">
          </div>
          <div class="middle">
            <ul>
              <li v-for="item,index in templateArr" :key="index">
                <div class="box">
                  <div class="inner">
                    <h1>{{item.title}}
                      <img v-show="index>0"  @click="templateArr.splice(index,1)"
                           src="../../../../public/img/icon/auto-x.png" alt="" class="autoX"></h1>
                    <el-select v-model="item.id" size="small">
                      <el-option label="请选择" value="" hidden></el-option>
                      <el-option v-for="item,index in treeTemplate" :key="index"
                      :label="item.name" :value="item.id"></el-option>
                    </el-select>
                  </div>
                </div>
                <img v-show="templateArr.length-1>index" class="right" src="../../../../public/img/icon/auto-right.png" alt="">
              </li>
              <li style="background-color: #fff">
                <img @click="templateArr.push({id:'',title:'客户打开前一封邮件后会收到'})"
                     class="add" src="../../../../public/img/icon/auto-add.png" alt="" title="添加邮件模板">
              </li>
            </ul>
          </div>
          <div class="the-frag">
            <img class="next" src="../../../../public/img/icon/auto-bottom.png" alt="">
          </div>
          <div class="bottom">
            <div class="bottom-box">
              <h2>打开邮件的用户是否转分组</h2>
              <div class="line-radio">
                <el-radio v-model="ruleForm.doChange" label="1">是</el-radio>
                <el-radio v-model="ruleForm.doChange" label="0">否</el-radio>
              </div>
              <div class="box" v-show="ruleForm.doChange==1">
                <div class="inner">
                  <h1>请选择转移分组：</h1>
                  <el-cascader size="small"  v-model="changeGroupIdArr" class="input"
                               props.checkStrictly=true @change="(value) => handleChange(value, 'changeGroupId')"
                               change-on-select
                               :options="treeMan"
                               :props="{ expandTrigger: 'hover',label: 'text', value: 'id', children: 'children'}"
                  ></el-cascader>
                </div>
              </div>
            </div>
          </div>
        </div>

      </el-form-item>
      <el-form-item class="common-btn">
        <el-button size="small" @click="$router.go(-1)">取 消</el-button>
        <el-button  size="small" type="primary" id="submitEmail"
                    @click="submit('ruleForm')" :loading="loading">{{loading?'保存中':'确 定'}}</el-button>
      </el-form-item>
    </el-form>
    <VueTour ref="vueTour" :steps="steps" prev="/automation/mailAutomation"
             type="1" path="/automation/mailAutomation"></VueTour>
  </div>
</template>

<script>
    import {mapState} from 'vuex'
    import {mailList} from "@/api/automation/mail"
    import {saveRules, updateRule, mailTemplateDetail, getGroup} from "@/api/mailAutomation"
    import VueTour from '@/components/automation/VueRour'
    import { getRollbackID} from '@/util/util'
    export default {
        name: "detail",
        components: {VueTour},
        data() {
            return {
                ruleForm: {
                    name: '',//规则名称
                    sendEmail: '',//发送邮箱
                    startDate: '',//开始时间
                    endDate: '',//结束时间
                    templates: [],//模板ID集合
                    doChange: '0',//是否转分组
                    cutGroupId: '',//选择分组 ID
                    changeGroupId: '',//目标转移分组ID
                    timeArr: [],//时间变量
                },
                cutGroupIdArr:[],//初始化分组
                changeGroupIdArr:[],//转换分组
                templateArr: [{id: '',title:'选择发送模板：'}],//模板数组集合
                rules: {
                    name: [
                        {required: true, message: '请输入规格名称', trigger: 'blur'},
                        {min: 1, max: 20, message: '长度在 1 到 20 个字符', trigger: 'blur'}
                    ],
                    sendEmail: [
                        {required: true, message: '请选择邮箱', trigger: 'blur'}
                    ],
                    timeArr: [{required: true, message: '请选择有效时间', trigger: 'blur'}],
                    templates: [
                        {required: true, message: ' ', trigger: 'blur'}
                    ],
                },
                id: '',
                title: '',
                steps: [
                    {
                        target: '#submitEmailRule',  // We're using document.querySelector() under the hood
                        content: '【邮件自动化规则创建】<br>第四步，点击保存按钮创建邮件一条自动化规则'
                    },
                ],
                pickerOptions: {
                    disabledDate: time => {
                        return time.getTime() < Date.now() - 8.64e7
                    }
                },
                treeTemplate:[],//模板列表
                treeMan:[],//客户分组
                loading: false
            }
        },
        computed: {
            ...mapState(['common'])
        },
        mounted() {
            if (this.common.isFirstEmail) {
                this.$nextTick(() => {
                    this.$refs.vueTour.init();//初始化
                })
            }
            //获取模板列表，分组
            this.getTemplate();
            //获取参数
            const type = this.$route.query.type;
            if (type == 1) {
                this.title = '复制'
                this.id= this.$route.params.id;
                this.getDetail();
            } else if (type == 2) {
                this.title = '编辑';
                this.id= this.$route.params.id;
                this.getDetail();
            } else {
                this.getGroup();
                this.title = '添加新的';
            }
        },
        methods: {
            submit(){
                if(!this.isRule())return;
                this.$refs['ruleForm'].validate((valid) => {
                    if (valid) {
                        this.loading = true;
                        this.ruleForm.startDate = this.ruleForm.timeArr[0];
                        this.ruleForm.endDate = this.ruleForm.timeArr[1];
                        let params = JSON.parse(JSON.stringify(this.ruleForm))
                        params.doChange = parseInt(params.doChange)
                        delete params.timeArr;
                        if (this.title == '复制') {
                            delete this.ruleForm.id
                        }
                        if (this.ruleForm.id) {//保存
                            updateRule(params).then(res => {
                                this.dealResult(res)
                            }).catch(() => {
                                this.loading = false;
                            })
                        } else {//新增
                            saveRules(params).then(res => {
                                this.dealResult(res)
                            }).catch(() => {
                                this.loading = false;
                            })
                        }
                    } else {
                        return false;
                    }
                });
            },
            //获取初始化详情
            getDetail(){
                mailTemplateDetail(this.id).then(res=>{
                    if(res.data.success){
                        this.templateArr =[];
                        this.ruleForm.templates=[];
                        //转换参数
                        const result = res.data.data;
                        this.ruleForm.id = result.id;
                        this.ruleForm.name = result.name;
                        this.ruleForm.sendEmail = result.sendEmail;
                        this.ruleForm.startDate = result.startDate;
                        this.ruleForm.endDate = result.endDate;
                        this.ruleForm.cutGroupId = result.cutGroupId;
                        this.ruleForm.changeGroupId = result.changeGroupId;
                        this.ruleForm.doChange = result.doChange?'1':'0';
                        this.ruleForm.timeArr.push(this.ruleForm.startDate);
                        this.ruleForm.timeArr.push(this.ruleForm.endDate);
                        for(let index in result.emailRuleGroupTemplates){
                            const item = result.emailRuleGroupTemplates[index];
                            this.ruleForm.templates.push(item.templateId);
                            this.templateArr.push({
                                title:index==0?'选择发送模板':'客户打开前一封邮件后会收到',
                                id:item.templateId
                            })
                        }
                        this.getGroup();
                    }
                }).catch(err=>{
                    console.log(err)
                })

            },
            isRule(){//数据判断是否为空 true -
                let frag = true;
                if(this.ruleForm.doChange==1){//转分组
                    if(this.ruleForm.cutGroupId==this.ruleForm.changeGroupId){
                        this.$message({
                            type: "success",
                            message: '目标用户已存在要转移的分组中，请重新选择要转移到的分组名称'
                        });
                        return false;
                    }else{
                        if(this.ruleForm.cutGroupId==''){
                            this.$message({
                                type: "success",
                                message: '请选择目标用户分组'
                            });
                            return false;
                        }else if(this.ruleForm.changeGroupId==''){
                            this.$message({
                                type: "success",
                                message: '请选择要转移到的分组名称'
                            });
                            return false;
                        }
                    }
                }
                this.ruleForm.templates=[];
                for(let item of this.templateArr){
                    if(item.id==''){
                        frag=false;
                    }else{
                        this.ruleForm.templates.push(item.id)
                    }
                }
                if(!frag){
                    this.$message({
                        type: "success",
                        message: '请填写规则详情完整'
                    });
                }
                console.log(frag)
                return frag
            },
            getTemplate() {
                mailList('', 1, 100, '').then(res => {
                    if (res.data.success) {
                        this.treeTemplate = res.data.data.records;
                        if (this.treeTemplate.length == 0) {
                            this.$alert('您还尚未创建邮件模板，请先创建！', '提示', {
                                confirmButtonText: '确定',
                                callback: action => {
                                    this.$router.push('/automation/template/mailDetail/-1')
                                }
                            });
                        }
                    }
                })
            },
            getGroup() {
                getGroup(0).then(res => {
                    if (res.data.success) {
                        this.treeMan= res.data.data;
                        if(this.id!=-1){
                            this.cutGroupIdArr =this.changeString(getRollbackID(this.treeMan, this.ruleForm.cutGroupId))
                            if( this.ruleForm.doChange=='1'){
                                this.changeGroupIdArr = this.changeString(getRollbackID(this.treeMan, this.ruleForm.changeGroupId))
                            }
                        }
                    }
                })
            },
            dealResult(res) {
                this.loading = false;
                if (res.data.success) {
                    this.$message({
                        type: "success",
                        message: res.data.msg
                    });
                    this.$router.go(-1)
                } else {
                    this.$message({
                        type: "success",
                        message: res.data.msg
                    });
                }
            },
            handleChange(val, name) {
                this.ruleForm[name] = val[val.length - 1];
            },
            changeString(arr){
                let end = []
                arr.map(item => {
                    end.push(item.toString())
                })
                return end;
            }
        }
    }
</script>

<style lang="scss">
  $width: 224px;
  $bg: #F5F5F5;
  .automation-add {

    form.el-form.demo-ruleForm {
      padding: 0 10px;
      .line{
        display: flex;
      }

      label.el-form-item__label {
        color: #000;
      }

      .rule-detail {

        .box {
          padding: 10px 15px;
          background-color: $bg;
          border-radius: 10px;
          width: $width;

          .inner {
            width: 200px;
            height: 74px;
            padding: 0 12px 5px 12px;
            text-align: center;
            background: rgba(216, 228, 242, 1);
            border-radius: 10px;
          }

          h1 {
            font-size: 14px;
            color: #000;
            height: 30px;
            font-weight: 600;
            line-height: 37px;
            .autoX{
              width: 12px;
              height: 12px;
            }
          }
        }

        .middle {
          display: flex;
          align-items: center;
          max-width: 1009px;
          ul {
            display: flex;
            flex-wrap: wrap;
            li{
              display: flex;
              align-items: center;
              background-color: #f5f5f5;
              margin-bottom: 10px;
              .box{
                border-radius: 0;
              }
            }
            li:first-child{
              .box{
                border-top-left-radius: 10px;
                border-bottom-left-radius: 10px;
              }
            }
          }
          .add{
            width: 62px;
            height: 62px;
            margin-left: 20px;

          }
        }

        .bottom {
          width: 254px;
          background-color: #F5F5F5;
          border-radius: 10px;
          text-align: center;

          .bottom-box {
            h2 {
              font-size: 14px;
              color: #000;
              font-weight: normal;
              height: 30px;
              line-height: 39px;
            }

            .box {
              padding-top: 0;
            }
          }
        }

        .the-frag {
          width: 254px;
          text-align: center;

          img.next {
            width: 26px;
            height: 22px;
            margin-top: 12px;
          }
        }
        img.right{
          width: 38px;
          height: 18px;
          margin: 0 21px;
        }

      }
    }


  }
</style>
